package com.huluobo.kotlindemoim1911a2

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.SoundPool
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.TaskStackBuilder
import com.huluobo.kotlindemoim1911a2.adapter.EMMessageListenerAdapter
import com.huluobo.kotlindemoim1911a2.ui.activity.ChatActivity
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMOptions
import com.hyphenate.chat.EMTextMessageBody

/**
 * Created by lc on 2022/10/18.
 */
class IMApplication : Application() {
    companion object {
        lateinit var instance: IMApplication
        //因为伴生函数类似于静态代码块,在类被创建时调用,此时还没有走application的生命周期
        //也就是会在onCreate之前调用,这样肯定会产生空指针
        //使用lateinit,则会在onCreate之后调用
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    val soundPool: SoundPool = SoundPool.Builder().setMaxStreams(10).build()

    val duan by lazy {
        soundPool.load(instance, R.raw.duan, 0)
    }

    val yulu by lazy {
        soundPool.load(instance, R.raw.yulu, 0)
    }

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            //判断当前应用厨余前台还是后台
            if (isForeground()) {
                soundPool.play(duan, 1f, 1f, 0, 0, 1f)
            } else {
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
                //当应用程序处于后台位置,接收消息时需要弹出通知
                showNotification(messages)
            }
        }
    }

    private fun showNotification(messages: MutableList<EMMessage>?) {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        messages?.forEach {
            var contentText = "非文本消息"
            if (it.type == EMMessage.Type.TXT) {
                contentText = (it.body as EMTextMessageBody).message
            }//[图片][表情][视频]

            val intent = Intent(this, ChatActivity::class.java)
            intent.putExtra("username", it.conversationId())

            val taskStackBuilder =
                TaskStackBuilder.create(this).addParentStack(ChatActivity::class.java)
                    .addNextIntent(intent)//首先跳转到mainActivity,再跳转到ChatActivity

            val pendingIntent =
                taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

            val notification = Notification.Builder(this)
                .setContentTitle(getString(R.string.receive_new_message))//通知的标题
                .setContentText(contentText)//通知的内容
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.avatar1))//通知中的大图标
                .setSmallIcon(R.mipmap.ic_contact)//状态栏上的小图标
                .setContentIntent(pendingIntent)//点击跳转的intent
                .setAutoCancel(true)//设置自动回弹
                .setFullScreenIntent(pendingIntent, true)//设置当有其他app处于全屏状态时,当前app通知的优先级
                .build()
            notificationManager.notify(1, notification)

        }
    }

    private fun isForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (runningAppProcess in activityManager.runningAppProcesses) {
            if (runningAppProcess.processName == packageName) {
                //找到了当前运行的app的进程
                //判断当前app运行的关键级是否等于处于前台的关键级
                return runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
            }
        }
        return false
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        val options = EMOptions()
        options.appKey = "moroks#kotlinim1911a2"
        EMClient.getInstance().init(this, options)

        EMClient.getInstance().chatManager().addMessageListener(messageListener)

        soundPool.play(duan, 1f, 1f, 0, 0, 1f)
        soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
    }
}